import base64

import streamlit as st
import pandas as pd
from xml import etree

import requests
import json


# 将图片转换成base64格式（在Web上，流应用程序都是通过发送HTML代码来实现的。）
def set_png_as_page_bg(png_file):
    # Encoding the png_file provided to base64
    with open(png_file, 'rb') as f:
        img = f.read()
    b64 = base64.b64encode(img).decode()
    css = f'''
    <style>
    .stApp {{
        background-image: url("data:image/png;base64,{b64}");
        background-size: cover;
    }}
    </style>
    '''
    # Insert the CSS into the application
    # 将css样式写入web
    st.markdown(css, unsafe_allow_html=True)


st.markdown(
    """
<style>
.sidebar .sidebar-content {
    background: rgba(240, 242, 246, 0.2);
}
</style>
""",
    unsafe_allow_html=True,
)

# 选择对于的图片连接设置为背景图片
set_png_as_page_bg(r"bg.jpg")

st.markdown("# 城市空气质量智能化评估分析系统")

st.markdown("## 全国部分城市24信息检测表 ")


# 获取城市污染物的数据
def get_data(city="郑州"):
    """

    :param city:
    :return: {"items": items, # 污染物名字列表
                "values": values, # 对于污染物的指数
                "aqi": aqi} # 总体aqi指标
    """
    # 网页的地址
    url_city = 'https://www.zq12369.com/?city={0}&tab=city'

    import urllib.parse

    # 将城市名字解析成浏览器地址栏能识别的字符串
    city_code = urllib.parse.quote(city)

    # 请求网址并获取html的text文本
    res = requests.get(url_city.format(city_code)).text

    from bs4 import BeautifulSoup

    # 获取BeautifulSoup对象，用于解析文本
    html = BeautifulSoup(res, "html.parser")

    # 获取aqi的值
    aqi = html.find('div', class_='aqi').text  # aqi

    # 获取污染物项的div列表
    items = html.find('div', class_='aqidetail').find_all("div", class_=['item bglevel1'])

    # 获取对应值的div列表
    values = html.find('div', class_='aqidetail').find_all("div", class_=['value'])

    # 从对应的列表中获取div.text并生成列表
    items = [a.text for a in items]
    values = [b.text for b in values]
    items.insert(0, "aqi")
    values.insert(0, aqi)
    # 将以上三个结果返回
    return {"items": items, "values": values}


@st.cache_data
def get_array():
    data = pd.read_csv(f"outputs/city/china_cities_20210111.csv")
    return data.iloc[:, 1:11]


# 生成markdown字符串
def write_markdown(items, values):
    res = "|"
    for i in items:
        res = res + i + "|"
    res = res + "\n"
    for i in range(len(items)):
        res = res + "---- |"
    res = res + "\n"
    for i in values:
        res = res + i + "|"

    st.markdown(res)


st.write(get_array())

st.text_input("需要预测的城市的数据", key="city_name")
city_name = st.session_state.city_name
st.markdown("## 实时数据")
st.markdown(f"### {city_name}")
try:
    write_markdown(**get_data(city_name))
except Exception as e:
    st.write(e)
